//
//  DataObject.m
//  微他
//
//  Created by 微他 on 14-8-5.
//  Copyright (c) 2014年 微他. All rights reserved.
//

#import "DataObject.h"

@implementation DataObject

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        _tableName = [self.className lowercaseString];
    }
    return self;
}

- (void)updateAll
{
    DbHelper *dbHelper = [DbHelper instance];
    [dbHelper executeByQueue:[self toReplaceSql]];
}
- (void)loadfromDB:(NSDictionary *)dic
{
    DbHelper *dbHelper = [DbHelper instance];
    NSMutableArray *temp = [NSMutableArray array];
    NSArray *allkeys = [dic allKeys];
    for (int i=0; i<allkeys.count; i++) {
        NSMutableString *string = [NSMutableString stringWithFormat:@"%@=%@",allkeys[i],dic[allkeys[i]]];
        [temp addObject:string];
    }
    NSMutableString *sqlString = [NSMutableString stringWithFormat:@"select * from %@ where %@",_tableName,[Common implode:temp separator:@" And "]];
    [dbHelper querySingLeDbToObjectArray:[self class] object:self sql:sqlString];
}


- (NSString *)toReplaceSql
{
    NSArray *allkeys = self.getPropertyList;
    NSMutableString *sqlString = [NSMutableString stringWithFormat:@"REPLACE INTO %@ (",_tableName];
    for (int i=0; i<allkeys.count; i++) {
        [sqlString appendFormat:@"\'%@\'",allkeys[i]];
        if (i != allkeys.count - 1) {
            [sqlString appendString:@","];
            continue;
        }
        [sqlString appendString:@")VALUES("];
    }
    for (int i=0; i<allkeys.count; i++) {
        [sqlString appendFormat:@"\'%@\'",[self valueForKey:allkeys[i]]];
        if (i != allkeys.count - 1) {
            [sqlString appendString:@","];
            continue;
        }
        [sqlString appendString:@")"];
    }
//    NSLog(@"%@",sqlString);
    return sqlString;
}

- (void)clearAllData
{
    NSArray *allkeys = self.getPropertyList;
    for (int i=0; i<allkeys.count; i++) {
        [self setValue:@"" forKey:allkeys[i]];
    }
}

@end
